'use client';

import { useState, useEffect } from 'react';
import { X, Save } from 'lucide-react';
import { Token } from '../types/token';

interface StrategyModalProps {
  isOpen: boolean;
  onClose: () => void;
  token: Token;
  onSaved: () => void;
}

export default function StrategyModal({ isOpen, onClose, token, onSaved }: StrategyModalProps) {
  const [formData, setFormData] = useState({
    isEnabled: false,
    rsiBuyThreshold: 30,
    rsiSellThreshold: 60,
    buyAmountSol: 3.0,
    buyAmountBnb: 0.5,
    buyAmountEth: 0.1,
    firstDipPercent: 20,
    secondDipPercent: 30,
    maxPositions: 3
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    if (token.strategy) {
      setFormData({
        isEnabled: token.strategy.isEnabled,
        rsiBuyThreshold: token.strategy.rsiBuyThreshold,
        rsiSellThreshold: token.strategy.rsiSellThreshold,
        buyAmountSol: token.strategy.buyAmountSol,
        buyAmountBnb: token.strategy.buyAmountBnb,
        buyAmountEth: token.strategy.buyAmountEth,
        firstDipPercent: token.strategy.firstDipPercent,
        secondDipPercent: token.strategy.secondDipPercent,
        maxPositions: token.strategy.maxPositions
      });
    }
  }, [token]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    setError('');

    try {
      const response = await fetch('/api/strategies', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          tokenId: token.id,
          ...formData
        }),
      });

      if (response.ok) {
        onSaved();
        onClose();
      } else {
        const errorData = await response.json();
        setError(errorData.error || '保存策略失败');
      }
    } catch (error) {
      setError('网络错误，请重试');
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, type, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : parseFloat(value) || 0
    }));
  };

  if (!isOpen) return null;

  const getBuyAmountLabel = () => {
    switch (token.chain) {
      case 'SOLANA':
        return 'SOL';
      case 'BSC':
        return 'BNB';
      case 'BASE':
        return 'ETH';
      default:
        return 'ETH';
    }
  };

  const getCurrentBuyAmount = () => {
    switch (token.chain) {
      case 'SOLANA':
        return formData.buyAmountSol;
      case 'BSC':
        return formData.buyAmountBnb;
      case 'BASE':
        return formData.buyAmountEth;
      default:
        return formData.buyAmountEth;
    }
  };

  const updateBuyAmount = (value: number) => {
    switch (token.chain) {
      case 'SOLANA':
        setFormData(prev => ({ ...prev, buyAmountSol: value }));
        break;
      case 'BSC':
        setFormData(prev => ({ ...prev, buyAmountBnb: value }));
        break;
      case 'BASE':
        setFormData(prev => ({ ...prev, buyAmountEth: value }));
        break;
    }
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
        {/* 头部 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
          <h3 className="text-lg font-medium text-gray-900 dark:text-white">
            {token.symbol} 交易策略配置
          </h3>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
          >
            <X className="w-6 h-6" />
          </button>
        </div>

        {/* 表单内容 */}
        <form onSubmit={handleSubmit} className="p-6 space-y-6">
          {error && (
            <div className="bg-red-50 dark:bg-red-900 border border-red-200 dark:border-red-700 rounded-lg p-4">
              <p className="text-red-800 dark:text-red-200">{error}</p>
            </div>
          )}

          {/* 启用状态 */}
          <div className="flex items-center">
            <input
              type="checkbox"
              id="isEnabled"
              name="isEnabled"
              checked={formData.isEnabled}
              onChange={handleChange}
              className="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600"
            />
            <label htmlFor="isEnabled" className="ml-2 text-sm font-medium text-gray-900 dark:text-gray-300">
              启用自动交易
            </label>
          </div>

          {/* RSI 阈值 */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                RSI买入阈值
              </label>
              <input
                type="number"
                name="rsiBuyThreshold"
                value={formData.rsiBuyThreshold}
                onChange={handleChange}
                className="input"
                min="0"
                max="100"
                step="0.1"
              />
              <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                RSI低于此值时买入
              </p>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                RSI卖出阈值
              </label>
              <input
                type="number"
                name="rsiSellThreshold"
                value={formData.rsiSellThreshold}
                onChange={handleChange}
                className="input"
                min="0"
                max="100"
                step="0.1"
              />
              <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                RSI高于此值时卖出
              </p>
            </div>
          </div>

          {/* 买入金额 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
              每次买入金额 ({getBuyAmountLabel()})
            </label>
            <input
              type="number"
              value={getCurrentBuyAmount()}
              onChange={(e) => updateBuyAmount(parseFloat(e.target.value) || 0)}
              className="input"
              min="0"
              step="0.1"
            />
            <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
              每次买入信号触发时的投入金额
            </p>
          </div>

          {/* 补仓策略 */}
          <div className="space-y-4">
            <h4 className="text-sm font-medium text-gray-900 dark:text-white">补仓策略</h4>
            
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  首次补仓跌幅 (%)
                </label>
                <input
                  type="number"
                  name="firstDipPercent"
                  value={formData.firstDipPercent}
                  onChange={handleChange}
                  className="input"
                  min="0"
                  max="100"
                  step="1"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  二次补仓跌幅 (%)
                </label>
                <input
                  type="number"
                  name="secondDipPercent"
                  value={formData.secondDipPercent}
                  onChange={handleChange}
                  className="input"
                  min="0"
                  max="100"
                  step="1"
                />
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                最大持仓次数
              </label>
              <input
                type="number"
                name="maxPositions"
                value={formData.maxPositions}
                onChange={handleChange}
                className="input"
                min="1"
                max="10"
                step="1"
              />
              <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                包括首次买入和补仓的总次数
              </p>
            </div>
          </div>

          {/* 策略说明 */}
          <div className="bg-blue-50 dark:bg-blue-900 rounded-lg p-4">
            <h4 className="text-sm font-medium text-blue-900 dark:text-blue-100 mb-2">
              策略说明
            </h4>
            <ul className="text-xs text-blue-800 dark:text-blue-200 space-y-1">
              <li>• RSI低于{formData.rsiBuyThreshold}时买入{getCurrentBuyAmount()} {getBuyAmountLabel()}</li>
              <li>• RSI高于{formData.rsiSellThreshold}时全部卖出</li>
              <li>• 首次买入后下跌{formData.firstDipPercent}%时补仓一次</li>
              <li>• 继续下跌{formData.secondDipPercent}%时再补仓一次</li>
              <li>• 最多持仓{formData.maxPositions}次</li>
            </ul>
          </div>

          {/* 按钮 */}
          <div className="flex justify-end space-x-4">
            <button
              type="button"
              onClick={onClose}
              className="btn-secondary"
            >
              取消
            </button>
            <button
              type="submit"
              disabled={isSubmitting}
              className="btn-primary flex items-center space-x-2"
            >
              <Save className="w-4 h-4" />
              <span>{isSubmitting ? '保存中...' : '保存策略'}</span>
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
